package com.itheima.service.mongo.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Component;

@Component  // redis主键自增器
public class RedisIDService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // 提供获取自增id方法
    public Long getNextID(String collectionName) {
        // 1.判断此表名的key是否存在，不存在设置初始值
        if (!stringRedisTemplate.hasKey("pid:" + collectionName)) {
            RedisAtomicLong redisAtomicLong = new RedisAtomicLong("pid:" + collectionName, stringRedisTemplate.getConnectionFactory());
            redisAtomicLong.set(10000);
        }

        // 2.存在+1并返回
        RedisAtomicLong redisAtomicLong = new RedisAtomicLong("pid:" + collectionName, stringRedisTemplate.getConnectionFactory());
        return redisAtomicLong.getAndIncrement();
    }
}
